const path = require('path');
const fs = require('fs');
const { parse } = require('csv-parse/sync');

const DATA_DIR = path.join(process.cwd(), 'excel', '06-21');
const DB_PATH = path.join(process.cwd(), 'data', 'json-database.json');

async function manualImport() {
  try {
    console.log('开始手动导入数据...');
    
    // 读取当前数据库
    const dbContent = fs.readFileSync(DB_PATH, 'utf-8');
    const db = JSON.parse(dbContent);
    
    const DEVICE_TABLE_FILES = [
      '设备表-配管专业.csv',
      '设备表-电气专业.csv',
      '设备表-暖通专业.csv',
      '设备表-通信专业.csv',
      '设备表-仪表专业.csv',
    ];
    
    // 为每个专业维护独立的设备计数器
    const deviceCounters = {
      '配管专业': 1,
      '电气专业': 1,
      '暖通专业': 1,
      '通信专业': 1,
      '仪表专业': 1
    };
    
    let totalDevices = 0;
    
    for (const filename of DEVICE_TABLE_FILES) {
      const specialty = filename.replace('设备表-', '').replace('.csv', '');
      const filePath = path.join(DATA_DIR, filename);
      
      console.log(`\n处理文件: ${filename} (${specialty})`);
      
      // 尝试不同的编码格式
      let content;
      try {
        content = fs.readFileSync(filePath, 'utf-8');
      } catch (error) {
        console.log('UTF-8编码失败，尝试GBK编码...');
        content = fs.readFileSync(filePath, 'gb2312');
      }
      
      console.log(`文件内容前200字符: ${content.substring(0, 200)}`);
      
      try {
        const records = parse(content, { 
          columns: true, 
          skip_empty_lines: true,
          relax_column_count: true,
          delimiter: ','
        });
        
        console.log(`解析得到 ${records.length} 条记录`);
        
        if (records.length > 0) {
          console.log('第一条记录的键:', Object.keys(records[0]));
          console.log('第一条记录:', records[0]);
        }
        
        for (let i = 0; i < records.length; i++) {
          const record = records[i];
          const deviceName = record['设备表及材料表中的实体对象名称'];
          
          console.log(`第${i+1}条记录 - 设备名称: "${deviceName}"`);
          
          // 跳过空行或标题行
          if (!deviceName || 
              deviceName.trim() === '' ||
              deviceName.includes('专业') ||
              deviceName === '设备表及材料表中的实体对象名称') {
            console.log(`  -> 跳过: ${deviceName || 'undefined'}`);
            continue;
          }
          
          // 生成唯一的设备ID
          const specialtyPrefix = specialty === '配管专业' ? 'PP' :
                                specialty === '电气专业' ? 'EL' :
                                specialty === '暖通专业' ? 'HV' :
                                specialty === '通信专业' ? 'CM' :
                                'IN'; // 仪表专业
          
          const deviceNumber = deviceCounters[specialty].toString().padStart(4, '0');
          const uniqueDeviceId = `${specialtyPrefix}-${deviceNumber}`;
          
          const deviceData = {
            id: uniqueDeviceId,
            name: deviceName,
            classificationName: record['对应的对象分类标准中的中文名称'] || '',
            序号: record['序号'] || '',
            classificationCode: record['分类码'] || '',
            specialty: specialty,
            namingTableId: record['对象命名'] || '',
            positionTableId: record['位置信息'] || '',
            baseParamsTableId: record['基础参数'] || '',
            techSpecTableId: record['技术规格书'] || '',
            备注: record['备注'] || ''
          };
          
          console.log(`  -> 添加设备: ${deviceData.name} (${uniqueDeviceId}) - ${deviceData.specialty}`);
          db.devices.push(deviceData);
          totalDevices++;
          deviceCounters[specialty]++;
        }
      } catch (parseError) {
        console.error(`解析文件 ${filename} 失败:`, parseError);
      }
    }
    
    // 保存更新后的数据库
    fs.writeFileSync(DB_PATH, JSON.stringify(db, null, 2));
    
    console.log(`\n成功导入 ${totalDevices} 个设备！`);
    
    // 统计各专业设备数量
    const stats = {};
    db.devices.forEach(device => {
      stats[device.specialty] = (stats[device.specialty] || 0) + 1;
    });
    
    console.log('\n各专业设备统计:');
    Object.entries(stats).forEach(([specialty, count]) => {
      console.log(`${specialty}: ${count} 个设备`);
    });
    
  } catch (error) {
    console.error('导入失败:', error);
  }
}

// 执行导入
manualImport(); 